# when migrating tables, somethimes we will find the old data is 
# incompatibility with the current scheme, we should clean it up

namespace :data do

  desc 'remove all terminal which has invalid mac address'
  task :terminal => :environment do
    macs = []
    total = destroy = 0
    Terminal.all.each do |t|
      total += 1

      # normalize the mac
      # why we do this? The following statement will apply our new before_save
      # hook, this hook will make the mac downcase and add colon if no colon
      unless t.mac.empty?
        t.updated_at = Time.now
        t.save
      end
      
      if t.mac.empty? || macs.include?(t.mac) || t.mac !~ /\A([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}\z/
        destroy += 1
        puts "invalid mac: #{t.mac}, removed: #{destroy}"
        t.destroy
      else
        macs << t.mac
      end
    end
    puts "Terminal-Total:#{total} - Removed:#{destroy}"
  end

  desc 'terminal is_latest update'
  task :terminal__is_latest => :environment do
    latest = TerminalVersion.latest
    Terminal.all.each do |t|
      t.update_attribute(:is_latest, latest == t.version)
    end
  end

  desc 'account detail info update'
  task :account_detail_info_update => :environment do
    Account.where(card_type: nil).all.each do |account|
      account.insert_detail_info
      account.save if account.valid?
    end
  end

  desc 'fix the counter cache was' 
  task :counter_update => :environment do
    TerminalGroup.find_each do |u|
      TerminalGroup.reset_counters u.id, :terminals
    end
    AccountGroup.find_each do |u|
      AccountGroup.reset_counters u.id, :accounts
    end
  end

  desc 'account firsted_signin init'
  task :account_firsted_signin_init => :environment do
    Account.all.each do |account|
      firsted_signin = account.account_signins.order(:id).first
      if firsted_signin
        account.update_column(:firsted_signin, firsted_signin.created_at)
        account.update_column(:register_terminal_id, firsted_signin.terminal_id)
      end
    end
  end

  desc "invalid watchings seconds remove"
  task :remove_invalid_wathcing => :environment do
    Watching.where(["created_at < ? and seconds > ?","2014-02-26",100000]).all.each do |w|
      w.update_column(:seconds, w.seconds.to_s.last(3).to_i)
    end
  end

  desc 'remove terminal order without valid terminal'
  task :terminal_order => :environment do
    total = destroy = 0
    TerminalOrder.all.each do |t|
      unless t.terminal
        destroy += 1
        puts "invalid order: #{t.id}, removed: #{destroy}"
        t.destroy
      end
    end
    puts "TerminalOrder-Total:#{total} - Removed:#{destroy}"
  end

  desc 'empty watchings because add creditcard id'
  task :watching => :environment do
    Watching.delete_all
  end

  desc 'empty creditcards when fee cycle has come'
  task :creditcard => :environment do
    Creditcard.delete_all
  end

  desc 'traffic remove app traffic'
  task :traffic => :environment do
    Traffic.all.each do |t|
      t.destroy if t.device_type == 'App' || !t.device
    end
  end

  desc 'traffic stat init'
  task :traffic_stat => :environment do
    TrafficStatDay.delete_all
    TrafficStatWeek.delete_all
    TrafficStatMonth.delete_all
    Traffic.all.each do |t|
      t.update_stat
    end
  end

  desc 'driver account name init'
  task :driver_account_name_init => :environment do
    TerminalUser.all.each do |t|
      t.send(:driver_account_name_init)
    end
  end

  desc 'keep table not too big'
  task :limit, [:model, :size] => :environment do |task, args|
    size = args.size.to_i
    model = args.model.camelize.constantize

    if size <= 0
      puts "You are trying to remove all datas(#{model.count}) from #{args.model}, are you sure?(yes|no)"
      if ['yes', 'y'].include? $stdin.gets.chomp.downcase
        puts "deleting all datas from #{args.model}......"
        model.delete_all
        puts "Done!"
      else
        puts "Quit"
      end
    else
      count = model.count
      if count <= size
        puts "No need to trash: #{count} <= #{size}"
      else
        to_delete = count - size
        puts "You are trying to remove some datas(#{to_delete}) from #{args.model}, are you sure?(yes|no)"
        if ['yes', 'y'].include? $stdin.gets.chomp.downcase
          puts "deleting......"
          model.delete(model.order('id').limit(to_delete).map(&:id))
          puts "Done!"
        else
          puts "Quit"
        end
      end
    end
  end

  desc 'update values'
  task :add_branch => :environment do
    AppVersion.update_all(branch: 'public')
    TerminalVersion.update_all(branch: 'public')
  end

  desc 'wifi auto log out'
  task :wifi_check => :environment do
    accounts = WifiAccount.where(used: true).where('last_seen < ?', 10.minites.ago)
    accounts.each do |a|
      a.update_attributes(used: false, accident: true, used_or_released_at: Time.now, account_id: nil)

      wifi_log = WifiLog.where(wifi_account_id: a.id).where(end_at: nil).first
      if wifi_log
        wifi_log.update_attributes(end_at: Time.now, accident: true)
      end
    end
  end

  desc 'fix city_id of city_channel'
  task :fix_city_id_of_city_channel => :environment do
    CityChannel.all.collect(&:city_name).uniq.each do |city_name|
      puts city_name
      ch_id = CityChannel.where(:city_name => city_name).collect(&:city_id).compact.first
      CityChannel.where(:city_name => city_name).update_all({:city_id => ch_id})
    end
  end

  desc 'clear paper_trail data 3 months ago'
  task :paper_trail_clear => :environment do
    PaperTrail::Version.delete_all ["created_at < ?", 3.months.ago] 
  end

end